import errorCodes from '../../config/error-codes';
import errors from './errors';
import { Message, MessageBox } from '@csii/vx-web';
import { throttle } from '@csii/vx-util';
import { getContextData } from '@csii/vx-util';
import axios from 'axios';
import router from '@/router';

Message.error = throttle(Message.error, 1500, { trailing: false });
MessageBox.alert = throttle(MessageBox.alert, 1500, { trailing: false });

export const transformRequest = function (config) {
  const token = getContextData('token');
  if (token) {
    config.headers['X-Access-Token'] = token; // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  return config;
};

export const transformResponse = function (response) {
  let respData = response.data;
  // 开启保存mock
  if (process.env.VUE_APP_SAVE_JSON === 'true') {
    let path = response.config.url;
    if (path.indexOf('/') === 0) {
      path = path.slice(1);
    }
    path = path.replace(/\//g, '-');
    axios.post('http://localhost:3000/mock/path/', { data: respData, path: `${path}_${response.config.method}.json` });
    // 开启加密
  }
  // 和后端约定的成功业务逻辑的状态码（若是文件流也直接返回）
  if (respData.code === '200' || response.config.responseType === 'blob') {
    return respData;
  } else {
    if (response.data.code === '9001') {
      MessageBox.alert('很抱歉，登录已过期，请重新登录。', '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '放弃',
        cancelButtonClass: 'default-btn', // 取消按钮的自定义类名
        type: 'warning',
      }).then(() => {
        sessionStorage.clear();
        // 清空 vuex 用户信息
        // await dispatch('vxadmin/user/set', {}, { root: true });
        // 跳转路由
        router.push({
          name: 'login',
        });
      });
    } else {
      // 业务逻辑错误
      const code = respData.code;
      const message = respData.msg;
      throw new errors.BuessinessError(code, message);
    }
  }
};

const validateStatus = (status) => status >= 200 && status < 300;

export const catchError = function (error) {
  // axios 可能抛出的错误是 https://github.com/axios/axios/search?q=createError&unscoped_q=createError
  if (error && error.isAxiosError) {
    let message = error.message;
    const response = error.response;
    // http协议层错误处理 https://github.com/axios/axios/blob/885ada6d9b87801a57fe1d19f57304c315703079/lib/core/settle.js#L17
    if (response && !validateStatus(response.status)) {
      message = errorCodes.network[response.status];
      throw new errors.NetworkError(response.status, message);
    }
    if (/timeout/.test(message)) {
      // 客户端请求超时 https://github.com/axios/axios/blob/dc4bc49673943e35280e5df831f5c3d0347a9393/lib/adapters/xhr.js#L95
      message = '请求超时！';
    } else if (/aborted/.test(message)) {
      // 客户端主动取消 https://github.com/axios/axios/blob/dc4bc49673943e35280e5df831f5c3d0347a9393/lib/adapters/xhr.js#L73
      message = '请求被取消！';
    } else if (/^Network/.test(message)) {
      // 客户端网络连接失败 https://github.com/axios/axios/blob/dc4bc49673943e35280e5df831f5c3d0347a9393/lib/adapters/xhr.js#L83
      message = '网络连接错误！';
    } else {
      message = '未定义错误!!!';
    }
    throw new errors.ClientError(message);
  } else {
    throw error;
  }
};

// catch报错
export const errorTip = function (error, options) {
  Message.error(error.message);
  console.log(options);
};
